<?php

require_once dirname(__FILE__) . '/../lib/alumnoGeneratorConfiguration.class.php';
require_once dirname(__FILE__) . '/../lib/alumnoGeneratorHelper.class.php';

/**
 * alumno actions.
 *
 * @package    sistema_itec_new
 * @subpackage alumno
 * @author     Your name here
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class alumnoActions extends autoAlumnoActions {

    protected function buildQuery() {
        $query = parent::buildQuery();
        $query->innerJoin($query->getRootAlias() . '.Alumno a');
        return $query;
    }

    protected function processForm(\sfWebRequest $request, \sfForm $form) {
        $persona = $request->getParameter('persona');
        $persona['fecha_nacimiento'] = date('Y-m-d', strtotime(str_replace('/', '-', $persona['fecha_nacimiento'])));
        /*if (isset($persona['AntecedenteAcademico'])) {
            $req_anac = $persona['AntecedenteAcademico'];
            foreach ($req_anac as $key => $anac) {
                $req_anac[$key]['fecha'] = date('Y-m-d', strtotime(str_replace('/', '-', $anac['fecha'])));
            }
            $persona['AntecedenteAcademico'] = $req_anac;
        }
        $req_new_anac = $persona['new_AntecedenteAcademico'];
        foreach ($req_new_anac as $key => $anac) {
            $req_new_anac[$key]['fecha'] = date('Y-m-d', strtotime(str_replace('/', '-', $anac['fecha'])));
        }
        $persona['new_AntecedenteAcademico'] = $req_new_anac;*/
        $request->setParameter('persona', $persona);

        parent::processForm($request, $form);
    }

    public function executeCursado(sfWebRequest $request) {
        $persona = Doctrine::getTable('Persona')->findOneById($request->getParameter('id'));
        $this->forwardUnless($persona, 'home', 'index');
        $this->modulos_alumno = Doctrine::getTable('ModuloCohorte')->getUCDisponibles($persona->getId());
        $this->condiciones_cursado = Doctrine::getTable('CondicionCursado')->findAll();
    }

    public function executeInscribirCursado(sfWebRequest $request) {
        $persona = Doctrine::getTable('Persona')->findOneById($request->getParameter('id'));
        $this->forwardUnless($persona, 'home', 'index');

        $acuf = Doctrine::getTable('AlumnoCohorteUnidadFormacion')->findOneByAlumnoId($persona->getId());
        $incu = Doctrine::getTable('InscripcionCursado')->findByAlumnoCohorteUnidadFormacion($acuf->getId());
        $ids = array();
        foreach ($incu as $i) {
            $ids[] = $i->getId();
        }

        $modulos_inscribe = $request->getParameter('modulo');
        $conn = Doctrine_Manager::getInstance()->connection();
        try {
            $conn->beginTransaction();
            foreach ($modulos_inscribe as $key => $modulo) {
                $inscripcion = Doctrine::getTable('Alumno')->getInscripcion($key, $ids);
                if ($inscripcion) {
                    $ic = Doctrine::getTable('InscripcionCursado')->findOneById($inscripcion['inscripcion']);
                    $admc = Doctrine::getTable('AlumnoDocenteModuloCohorte')->findOneById($inscripcion['id']);
                    if ($modulo['condicion'] == 0) {
                        $admc->delete();
                        $ic->delete();
                    } else if ($modulo['condicion'] != $inscripcion['condicion']) {
                        $ic->setCondicionCursadoId($modulo['condicion']);
                        $ic->save();
                    }
                } else {
                    if ($modulo['condicion'] > 0) {
                        $dmc = Doctrine::getTable('DocenteModuloCohorte')->findOneByModuloCohorteId($key);
                        $ic = new inscripcionCursado();
                        $ic->setFechaInscripcion(date('Y-m-d'));
                        $ic->setPromocionable(1);
                        $ic->setAlumnoCohorteUnidadFormacionId($acuf->getId());
                        $ic->setCondicionCursadoId($modulo['condicion']);
                        $ic->save();

                        $admc = new AlumnoDocenteModuloCohorte();
                        $admc->setDocenteModuloCohorteId($dmc->getId());
                        $admc->setInscripcionCursadoId($ic->getId());
                        $admc->save();
                    }
                }
            }
            $conn->commit();
            $this->getUser()->setFlash('notice', 'La inscripción se ha realizado correctamente.');
            $this->redirect('alumno/cursado?id=' . $request->getParameter('id'));
        } catch (Exception $e) {
            $conn->rollback();
            $this->getUser()->setFlash('error', 'Se ha producido un error al guardar la inscripción.');
            $this->redirect('alumno/cursado?id=' . $request->getParameter('id'));
        }
    }

    public function executeExamenes(sfWebRequest $request) {
        $persona = Doctrine::getTable('Persona')->findOneById($request->getParameter('id'));
        $this->forwardUnless($persona, 'home', 'index');
        $this->examenes_alumno = Doctrine::getTable('examenAlumno')->getExamenesByAlumno($persona->getId());
        $this->condiciones = array(0 => 'No se inscribe', 1 => 'Regular', 2 => 'Libre', 3 => 'Promocionado', 4 => 'Equivalencia');
        if ($request->isMethod(sfRequest::POST)) {
            $examenes_alumno = $request->getParameter('examen_alumno');
            if ($request->getParameter('imprimir')) {
                $examenes = array();
                foreach ($this->examenes_alumno as $examen_alumno) {
                    if (isset($examenes_alumno[$examen_alumno->getId()]['imprimir'])) {
                        $examenes[] = $examen_alumno;
                    }
                }
                $html =  $this->getPartial('printComprobante', array('examenes' => $examenes, 'condiciones' => $this->condiciones, 'persona' => $persona));
                $pdf = new DOMPDF;
                $pdf->load_html($html);
                $pdf->set_paper('A4', 'portrait');
                $pdf->render();
                $pdf->stream('comprobante_'.date('Ymd').'.pdf', array('Attachment' => 0));
            } else {
                try {
                    $conn = Doctrine_Manager::getInstance()->connection();
                    $conn->beginTransaction();
                    foreach ($this->examenes_alumno as $examen_alumno) {
                        if ($examenes_alumno[$examen_alumno->getId()]['condicion'] == 0) {
                            $examen_alumno->delete();
                        } else {
                            $examen_alumno->setAusente(isset($examenes_alumno[$examen_alumno->getId()]['ausente']) ? : 0);
                            $examen_alumno->setPago(isset($examenes_alumno[$examen_alumno->getId()]['pagado']) ? : 0);
                            $examen_alumno->save();
                        }
                    }
                    $conn->commit();
                    $this->getUser()->setFlash('notice', 'Los cambios se han guardado correctamente.');
                    $this->redirect('examenes', array('id' => $persona->getId()));
                } catch (Exception $e) {
                    $conn->rollback();
                    $this->getUser()->setFlash('error', 'Se ha producido un error al guardar los datos.');
                    $this->redirect('examenes', array('id' => $persona->getId()));
                }
            }
        }
    }

    public function executePrintSummary(sfWebRequest $request) {
        $summary = Doctrine::getTable('Alumno')->getSummary();
        sfConfig::set('sf_web_debug', false);
        $filename = 'Alumnos_'.date('d-m-Y');
        header("Content-Type: application/vnd.ms-excel ; charset=UTF-8");
        header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
        return $this->renderPartial('printList1', array('summary' => $summary));
    }

    public function executePrintListadoPorLocalidad(sfWebRequest $request) {
        $summary = Doctrine::getTable('Alumno')->getSummary();
        sfConfig::set('sf_web_debug', false);
        $filename = 'Alumnos_por_Localidad';
        header("Content-Type: application/vnd.ms-excel ; charset=UTF-8");
        header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
        return $this->renderPartial('printList2', array('summary' => $summary));
    }

    public function executePrintASSummary(sfWebRequest $request) {
        $alumnos = Doctrine::getTable('Alumno')->findAlumnos();
        $datos = array(
            2 => array('carrera' => 'Analista de Sistemas de Computación', 'total' => 0, 'varones' => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0, 24 => 0, 25 => 0, 30 => 0, 'i_total' => 0, 'i_varones' => 0),
            3 => array('carrera' => 'Técnico Superior en Electromecánica', 'total' => 0, 'varones' => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0, 24 => 0, 25 => 0, 30 => 0, 'i_total' => 0, 'i_varones' => 0),
            4 => array('carrera' => 'Técnico Superior en Turismo', 'total' => 0, 'varones' => 0, 18 => 0, 19 => 0, 20 => 0, 21 => 0, 22 => 0, 23 => 0, 24 => 0, 25 => 0, 30 => 0, 'i_total' => 0, 'i_varones' => 0)
        );
        foreach ($alumnos as $alumno) {
            $udef = $alumno->getAlumnoCohorteUnidadFormacion()->getCohorteUnidadFormacion()->getUnidadFormacionId();
            $ingresante = $alumno->getAlumnoCohorteUnidadFormacion()->getCohorteUnidadFormacion()->getCohorte()->getAno() == '2013' ? true : false;
            $sexo = $alumno->getPersona()->getSexo();
            $edad = date('Y-m-d', strtotime('2013-06-30')) - date('Y-m-d', strtotime($alumno->getPersona()->getFechaNacimiento()));
            $datos[$udef]['total']++;
            if ($sexo == 'M') {
                $datos[$udef]['varones']++;
            }
            if ($ingresante) {
                $datos[$udef]['i_total']++;
                if ($sexo == 'M') {
                    $datos[$udef]['i_varones']++;
                }
            }
            switch (true) {
                case ($edad <= 18):
                    $datos[$udef][18]++;
                    break;
                case ($edad >= 19 && $edad <= 24):
                    $datos[$udef][$edad]++;
                    break;
                case ($edad >= 25 && $edad <= 29):
                    $datos[$udef][25]++;
                    break;
                case ($edad >= 30):
                    $datos[$udef][30]++;
                    break;
            }
        }
        sfConfig::set('sf_web_debug', false);
        $filename = 'Resumen_Alumnos';
        header("Content-Type: application/vnd.ms-excel ; charset=UTF-8");
        header('Content-Disposition: attachment; filename="' . $filename . '.xls"');
        return $this->renderPartial('printList3', array('datos' => $datos));
    }

}
